/**
 * Created by Administrator on 2018/4/4.
 */
/**
 * Created by lyp on 2017/8/1.
 */
$(document).ready(function(){
    user.loadTurnList();//加载数据表格
    user.bootstrapValidator();//表单验证
    user.searchTurn();//点击查询
});
var user = {};
(function(res){

    //表单验证
    res.bootstrapValidator=function(){
        $("#addTurnForm").bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                validating: 'glyphicon glyphicon-refresh'
            },
            fields:{
                validity:{
                    validators: {
                        notEmpty: {
                            message: '授权码有效期不能为空'
                        }
                    }
                },
                tokenSize:{
                    validators: {
                        notEmpty: {
                            message: '授权码有效期不能为空'
                        }
                    }
                }
            }
        });
    };
    //防止表单重复验证
    res.resetValidator=function(){
        $("form.required-validate").each(function() {
            var $form = $(this);
            $form.bootstrapValidator().on("success.form.bv",function(e){
                e.preventDefault();
            });
        });
    };
    //打开添加车辆管理的窗口
    res.openAddTurn=function(){
        $("#addTurnForm").data('bootstrapValidator').destroy();
        $('#addTurnForm').data('bootstrapValidator', null);
        res.bootstrapValidator();
        $("#addUserDialog").modal("show");
        var isTrue = true;
        res.resetTurnUser(isTrue);
        $("#organizationId,#phone,#email,#pwd,#zuserPwd,#userName").val("");
        $("#userType").val(0);
        $("#sex").val(0);
    };
    //提交添加用户的form表单
    res.submitTurnUser=function(){
        res.bootstrapValidator();
        var $form = $('#addTurnForm');
        var data = $form.data('bootstrapValidator');
        if (data) {
            // 修复记忆的组件不验证
            data.validate();
            if (!data.isValid()) {
                return false;
            }
        }
        res.resetValidator();
        var validity = $("#validity").val()
        if (validity == null || validity == '') {
            $("#validity").val(1);
        }
        var data = $("#addTurnForm").serialize();
        console.log(data)
        $.ajax({
            url:"/api/addOrUpDateToken",
            type:"post",
            data:data,
            dataType:"json",
            success:function(data){
                if (data.code==200&&data.isSuccess){
                    $("#addUserDialog").modal("hide");
                    layer.msg(data.msg);
                    $("#turnOverList").bootstrapTable("refresh");
                    $('#addTurnForm').bootstrapValidator('resetForm', true);
                }else{
                    layer.msg(data.msg);
                }
            }
        });
    };

    res.submitToken = function (data) {
        $.ajax({
            url:"/api/addOrUpDateToken",
            type:"post",
            data:data,
            dataType:"json",
            success:function(data){
                if (data.code==200&&data.isSuccess){
                    layer.msg(data.msg);
                    $("#turnOverList").bootstrapTable("refresh");
                    $('#addTurnForm').bootstrapValidator('resetForm', true);
                }else{
                    layer.msg(data.msg);
                }
            }
        });
    };


    //重置添加用户的form表单
    res.resetTurnUser=function(isTrue){
        $("#addTurnForm").find(":input").val("");
        $(".selectpicker").selectpicker('refresh');//刷新下拉框;
        $('#addTurnForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
    };
    /**
     * 初始化车辆管理表格
     */
    res.loadTurnList=function(type,vehiclName,base,status,numberTurn){
        $('#turnOverList').bootstrapTable('destroy');/*表格加载前先销毁原有数据*/
        $('#turnOverList').bootstrapTable({
            method: 'POST',
            url:"/api/getTokenPage",
            queryParamsType:'',
            queryParams:function (params) {
                console.log(params);
                pageSize = params.pageSize;
                pageNum = params.pageNumber;
                playerToken = params.searchText
                return {
                    pageSize:pageSize,
                    pageNum:pageNum,
                    playerTokens:playerToken
                }
            },
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            cache: false,     // 不缓存
            striped: true,    // 隔行加亮
            pagination: true, //是否显示分页
            toolbar: '#toobar',//工具列
            singleSelect:true, //单选
            clickToSelect:true,
            pageSize: 10,
            pageNumber: 1,     //初始化加载第一页，默认第一页
            pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
            sidePagination: "server",
            search: true,
            showRefresh: true,  //是否显示刷新按钮
            showColumns: true,
            columns:[
                {field: "select",title: "选择",checkbox: true,width: 60},
                {field: '',title: '序号',width: 60,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
                {field:"userName",title:"管理员",align:"center",valign:"middle",sortable:"true"},
                {field:"playerToken",title:"授权码",align:"center",valign:"middle",sortable:"true"},
                {field:"unit",title:"卡密时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {
                        if (value == 1) {
                            return "月卡"
                        }else if (value == 2) {
                            return "周卡"
                        } else if (value == 3) {
                            return "日卡"
                        }else if (value == 4) {
                            return row.validity;
                        }
                    }},
                {field:"status",title:"状态",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {
                        if (value == 0) {
                            return "未激活"
                        }else if (value == 1) {
                            return "已激活"
                        } else if (value == 2) {
                            return "已过期"
                        }else if (value == 3) {
                            return "已拉黑"
                        }
                    }},
                {field:"phone",title:"手机号",align:"center",valign:"middle",sortable:"true"},
                {field:"phoneNumber",title:"手机序列号",align:"center",valign:"middle",sortable:"true"},
                {field:"phoneType",title:"手机型号",align:"center",valign:"middle",sortable:"true"},
                {field:"createDate",title:"生成时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {
                        /*if(value==""||value==null){
                            return "";
                        }else{
                            return res.dateFormat(new Date(value),"yyyy-MM-dd")
                        }*/
                        return value;
                    }},
                {field:"blockTime",title:"拉黑时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {
                        /*if(value==""||value==null){
                            return "";
                        }else{
                            return res.dateFormat(new Date(value),"yyyy-MM-dd")
                        }*/
                        return value;
                    }},
                {field:"whiteTime",title:"拉白时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {
                        /*if(value==""||value==null){
                            return "";
                        }else{
                            return res.dateFormat(new Date(value),"yyyy-MM-dd")
                        }*/
                        return value;
                    }},
                {field:"activateDate",title:"激活时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {
                        /*if(value==""||value==null){
                            return "";
                        }else{
                            return res.dateFormat(new Date(value),"yyyy-MM-dd")
                        }*/
                        return value;
                    }},
                {field:"endDate",title:"到期时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {
                        /*if(value==""||value==null){
                            return "";
                        }else{
                            return res.dateFormat(new Date(value),"yyyy-MM-dd")
                        }*/
                        return value;
                    }},
                {field:"cz",title:"操作",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {
                        var type = row.status == 3 ? "拉白" : "拉黑";
                        var html = '';
                        html += "<span class='glyphicon glyphicon-edit' title='"+type+"' onclick='user.update("+index+")'></span> &nbsp;&nbsp;";
                        html += '<span class="glyphicon glyphicon-trash" title="删除" onclick="user.delete('+index+')"></span>';
                        return html;
                    }
                }
            ],
            onClickRow:function(row,ele){

            },
            formatLoadingMessage: function () {
                return "请稍等，正在加载中...";
            },
            formatNoMatches: function () {
                return '无符合条件的记录';
            },
            responseHandler: function(res) {
                console.log(res);
                var total ,rows;
                if (res.data!=null&&res.data.length!=0) {
                    total = res.count;
                    rows = res.data;
                }else {
                    total = 0;
                    rows = new Array();
                }
                return {
                    "total":total,//total,//总页数
                    "rows":rows  //数据
                };
            }

        });
    };

    res.changeUnit = function (){
        var unit = $("#unit").val();
        if (unit == 4) {
            $("#valDiv").show();
            $("#validity").val("")
        } else {
            $("#valDiv").hide();
            $("#validity").val(1)
        }
    }

    res.delete = function (index) {
        var data = $("#turnOverList").bootstrapTable('getData')[index];
        $.ajax({
            url:"/api/deleteToken",
            type:"post",
            data:data,
            dataType:"json",
            success:function(data){
                if (data.code==200&&data.isSuccess){
                    layer.msg(data.msg);
                    $("#turnOverList").bootstrapTable("refresh");
                    $('#addTurnForm').bootstrapValidator('resetForm', true);
                }else{
                    layer.msg(data.msg);
                }
            }
        });

    };


    res.update = function (index) {
        var data = $("#turnOverList").bootstrapTable('getData')[index];
        if (data.status == 3) {
            data.status=0;
        }else if (data.status == 1) {
            layer.msg("授权码已激活，禁止拉黑");
            return;
        } else if (data.status == 2) {
            layer.msg("授权码已过期，禁止拉黑");
            return;
        } else {
            data.status=3;
        }
        user.submitToken(data);
    };
    /*时间戳格式化*/
    res.dateFormat=function (now,mask) {
        var d = new Date(now);
        var zeroize = function (value, length)
        {
            if (!length) length = 2;
            value = String(value);
            for (var i = 0, zeros = ''; i < (length - value.length); i++)
            {
                zeros += '0';
            }
            return zeros + value;
        };
        return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0)
        {
            switch ($0)
            {
                case 'd': return d.getDate();
                case 'dd': return zeroize(d.getDate());
                case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
                case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
                case 'M': return d.getMonth() + 1;
                case 'MM': return zeroize(d.getMonth() + 1);
                case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
                case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
                    'November', 'December'][d.getMonth()];
                case 'yy': return String(d.getFullYear()).substr(2);
                case 'yyyy': return d.getFullYear();
                case 'h': return d.getHours() % 12 || 12;
                case 'hh': return zeroize(d.getHours() % 12 || 12);
                case 'H': return d.getHours();
                case 'HH': return zeroize(d.getHours());
                case 'm': return d.getMinutes();
                case 'mm': return zeroize(d.getMinutes());
                case 's': return d.getSeconds();
                case 'ss': return zeroize(d.getSeconds());
                case 'l': return zeroize(d.getMilliseconds(), 3);
                case 'L': var m = d.getMilliseconds();
                    if (m > 99) m = Math.round(m / 10);
                    return zeroize(m);
                case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
                case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
                case 'Z': return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
                default: return $0.substr(1, $0.length - 2);
            }
        });
    }



})(user);



